"use strict";

const { HtmlRspackPlugin } = require("@rspack/core");

const NAME = "HeadInjectPlugin";
/**
 * @import { Compiler, RspackPluginInstance } from "@rspack/core";
 */
/**
 * TODO: Option
 * @implements {RspackPluginInstance}
 */
class HeadInjectPlugin {
  /**
   * @param {{inject: string}} options
   */
  constructor(options) {
    this.options = options;
  }

  /**
   * @param {Compiler} compiler
   * @returns {void}
   */
  apply(compiler) {
    compiler.hooks.compilation.tap(NAME, (compilation) => {
      HtmlRspackPlugin.getCompilationHooks(compilation).beforeEmit.tap(
        NAME,
        (data) => {
          data.html = data.html.replace(
            /<\/head>/,
            `${this.options.inject}</head>`,
          );
          return data;
        },
      );
    });
  }
}
